﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace DnD.UI.Controls
{
    public partial class Navigator : UserControl
    {
        public NavigatorConfiguration Configuration { get; set; }

        public event EventHandler<NavigatorEventArgs> NodeSelected;

        public Navigator(NavigatorConfiguration configuration)
        {
            InitializeComponent();
            Configuration = configuration;
            GenerateNavigation();
        }

        public void GenerateNavigation()
        {
            navigatorTree.NodeMouseClick += NavigationContainer_TreeNodeSelected;

            foreach (NavigatorItem item in Configuration.Items)
                GenerateNode(item, navigatorTree.Nodes);

        }
        public void TriggerFirstNode()
        {
            if (navigatorTree.Nodes.Count > 0)
            {
                if (!(NodeSelected == null || NodeSelected.Method == null))
                {
                    TreeNode node = navigatorTree.Nodes[0];
                    NavigatorEventArgs args = new NavigatorEventArgs()
                    {
                        Node = node,
                        Item = (NavigatorItem)node.Tag
                    };
                    NodeSelected.Invoke(this, args);
                }
            }
        }
        public void GenerateNode(NavigatorItem item, TreeNodeCollection parent)
        {
            TreeNode node = new TreeNode();
            
            node.Text = item.Name;
            node.ToolTipText = item.ToolTip;
            foreach (NavigatorItem child in item.Children)
                GenerateNode(child, node.Nodes);
            if (item.LoadCollapsed)
                node.Collapse();
            else
                node.Expand();
            node.Tag = item;
            parent.Add(node);
        }
        public override void Refresh()
        {
            base.Refresh();
        }

        private void NavigationContainer_TreeNodeSelected(object sender, TreeNodeMouseClickEventArgs data)
        {
            if (NodeSelected == null || NodeSelected.Method == null)
                return;
            NavigatorEventArgs args = new NavigatorEventArgs()
            {
                Node = data.Node
                , Item = (NavigatorItem) data.Node.Tag
            };
            NodeSelected.Invoke(this, args);
        }

        
    }
}
